﻿#region zh-CHS 2006 - 2007 DemoSoft 团队 | en 2006 - 2007 DemoSoft Team

//     NOTES
// ---------------
//
// This file is a part of the G.O.S.E(Game Online Server Engine) for .NET.
//
//                 2006-2007 DemoSoft Team
//
//
// First Version : by H.Q.Cai - mailto:caihuanqing@hotmail.com

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published
 *   by the Free Software Foundation; either version 2.1 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

#region zh-CHS 包含名字空间 | en Include namespace
using System;
using System.Threading;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Demo_G.O.S.E.ServerEngine.Util;
using Demo_G.O.S.E.ServerEngine.World;
using Demo_G.O.S.E.ServerEngine.Common;
using Demo_G.O.S.E.ServerEngine.Network.DLL;
#endregion

namespace Demo_G.O.S.E.ServerEngine.Network
{
    /// <summary>
    /// 服务端监听
    /// </summary>
    [MultiThreadedSupportgAttribute( "当前的类所有成员都可锁定,支持多线程操作" )]
    public class Listener : IDisposable
    {
        #region zh-CHS 私有成员变量 | en Private Member Variables
        /// <summary>
        /// 监听到的客户端
        /// </summary>
        private Queue<ClientSocketHandler> m_Accepted   = new Queue<ClientSocketHandler>();
        /// <summary>
        /// 监听到的客户端的锁
        /// </summary>
        private object m_LockAccepted                   = new object();
        #endregion

        #region zh-CHS 构造和初始化和清理 | en Constructors and Initializers and Dispose
        /// <summary>
        /// 初始化构造
        /// </summary>
        public Listener()
        {
            m_SocketServer.ThreadEventAcceptor += new EventDelegateAcceptor( OnAcceptor );
        }

        #region zh-CHS 私有成员变量 | en Private Member Variables
        /// <summary>
        /// 是否已经处理过断开
        /// </summary>
        private volatile bool m_Disposed = false;
        #endregion
        /// <summary>
        /// 断开
        /// </summary>
        public void Dispose()
        {
            if ( m_Disposed == false && m_SocketServer != null)
            {
                m_Disposed = true;

                try
                {
                    m_SocketServer.StopServer();
                }
                catch
                {
                    Debug.WriteLine( "Listener.Dispose(...) - m_SocketMainServer.StopServer(...) Exception error!" );
                }

                m_SocketServer = null;
            }
        }
        #endregion

        #region zh-CHS 共有属性 | en Public Properties
        #region zh-CHS 私有成员变量 | en Private Member Variables
        /// <summary>
        /// 主监听处理
        /// </summary>
        private SocketServer m_SocketServer = new SocketServer();
        #endregion
        /// <summary>
        /// 监听的主处理
        /// </summary>
        public SocketServer ListenerSocket
        {
            get { return m_SocketServer; }
        }

        #region zh-CHS 私有成员变量 | en Private Member Variables
        /// <summary>
        /// 管理当前的世界服务
        /// </summary>
        private BaseWorld m_BaseWorld = null;
        #endregion
        /// <summary>
        /// 管理当前的世界服务
        /// </summary>
        public BaseWorld BaseWorld
        {
            get { return m_BaseWorld; }
        }

        #region zh-CHS BaseWorld 方法 | en BaseWorld Method
        /// <summary>
        /// 设置管理当前的世界服务
        /// </summary>
        /// <param name="baseWorld"></param>
        internal void SetBaseWorld( BaseWorld baseWorld )
        {
            m_BaseWorld = baseWorld;
        }
        #endregion

        #endregion

        #region zh-CHS 共有方法 | en Public Methods
        /// <summary>
        /// 开始服务
        /// </summary>
        /// <param name="port">端口</param>
        /// <returns></returns>
        public bool StartServer( int port )
        {
            if ( m_SocketServer.StartServer( port ) )
            {
                LOGs.WriteLine( LogMessageType.MSG_NOTICE, "新监听： 端口 {0} ", port );
                return true;
            }
            else
                return false;
        }

        /// <summary>
        /// 开始服务
        /// </summary>
        /// <param name="strHostNamePort">地址和端口</param>
        /// <returns></returns>
        public bool StartServer( string strHostNamePort )
        {
            if ( m_SocketServer.StartServer( strHostNamePort ) )
            {
                LOGs.WriteLine( LogMessageType.MSG_NOTICE, "新监听： 地址 {0} ", strHostNamePort );
                return true;
            }
            else
                return false;
        }
        #endregion

        #region zh-CHS 内部方法 | en Internal Method
        #region zh-CHS 私有静态成员变量 | en Private Static Member Variables
        /// <summary>
        /// 空的ClientSocketHandler数组
        /// </summary>
        private static ClientSocketHandler[] s_EmptySockets = new ClientSocketHandler[0];
        #endregion
        /// <summary>
        /// 获取新的联接过来的客户端
        /// </summary>
        /// <returns></returns>
        internal ClientSocketHandler[] Slice()
        {
            ClientSocketHandler[] l_ArrayReturn = s_EmptySockets;

            Monitor.Enter( m_LockAccepted );
            do
            {
                if ( m_Accepted.Count <= 0 )
                    break;

                l_ArrayReturn = m_Accepted.ToArray();

                // 清空数据,让它的调用着来处理这些数据
                m_Accepted.Clear();
            } while ( false );
            Monitor.Exit( m_LockAccepted );

            return l_ArrayReturn;
        }

        /// <summary>
        /// 释放指定的客户端到内存池里面
        /// </summary>
        /// <param name="clientSocketHandler"></param>
        internal void Free( ClientSocketHandler clientSocketHandler )
        {
            ServiceHandle l_ClientHandlerAtServer = clientSocketHandler.ListenerSocket;

            // 返回至内存池(ServiceHandleManager)
            ServiceHandleManager l_SocketHandlerManagerAtServer = l_ClientHandlerAtServer.SocketHandlerManager;
            l_SocketHandlerManagerAtServer.Value = IntPtr.Zero;
            m_SocketHandlerManagerAtServerPool.ReleasePoolContent( l_SocketHandlerManagerAtServer );

            // 返回至内存池(ServiceHandleManager)
            l_ClientHandlerAtServer.Value = IntPtr.Zero;
            l_ClientHandlerAtServer.SocketHandlerManager = null;
            m_ClientHandlerAtServerPool.ReleasePoolContent( l_ClientHandlerAtServer );

            // 返回至内存池(ClientSocketHandler)
            m_ClientSocketHandlerPool.ReleasePoolContent( clientSocketHandler );
        }
        #endregion

        #region zh-CHS 私有的事件处理函数 | en Private Event Handlers
        #region zh-CHS 私有成员变量 | en Private Member Variables
        /// <summary>
        /// 
        /// </summary>
        private ProcessMessageBlockPool<ClientSocketHandler> m_ClientSocketHandlerPool = new ProcessMessageBlockPool<ClientSocketHandler>( "Listener - ClientSocketHandler", 1024 );
        /// <summary>
        /// 
        /// </summary>
        private ProcessMessageBlockPool<ServiceHandle> m_ClientHandlerAtServerPool = new ProcessMessageBlockPool<ServiceHandle>( "Listener - ServiceHandle", 1024 );
        /// <summary>
        /// 
        /// </summary>
        private ProcessMessageBlockPool<ServiceHandleManager> m_SocketHandlerManagerAtServerPool = new ProcessMessageBlockPool<ServiceHandleManager>( "Listener - ServiceHandleManager", 1024 );
        #endregion
        /// <summary>
        /// 连接新的客户端的处理
        /// </summary>
        /// <param name="NonceClientHandler"></param>
        /// <param name="AllHandlerManager"></param>
        /// <param name="ClientHandlerAtServer"></param>
        private void OnAcceptor( ServiceHandle nonceClientHandler, ServiceHandleManager allHandlerManager, out ServiceHandle clientHandlerAtServer )
        {
            clientHandlerAtServer = null;

            SocketConnectEventArgs l_eventArgs = new SocketConnectEventArgs( nonceClientHandler );
            EventSink.InvokeSocketConnect( l_eventArgs );

            // 如果允许连接
            if ( l_eventArgs.AllowConnection )
            {
                ServiceHandle l_ClientHandlerAtServer = m_ClientHandlerAtServerPool.AcquirePoolContent();
                if ( l_ClientHandlerAtServer == null )
                {
                    Debug.WriteLine( "Listener.OnAcceptor(...) - l_ClientHandler == null error!" );

                    return;
                }
                l_ClientHandlerAtServer.Value = nonceClientHandler.Value;


                ServiceHandleManager l_SocketHandlerManager = m_SocketHandlerManagerAtServerPool.AcquirePoolContent();
                if ( l_SocketHandlerManager == null )
                {
                    Debug.WriteLine( "Listener.OnAcceptor(...) - l_SocketHandlerManager == null error!" );

                    m_ClientHandlerAtServerPool.ReleasePoolContent( l_ClientHandlerAtServer );

                    return;
                }
                l_ClientHandlerAtServer.SocketHandlerManager = l_SocketHandlerManager;
                l_ClientHandlerAtServer.SocketHandlerManager.Value = allHandlerManager.Value;


                ClientSocketHandler l_ClientSocketHandler = m_ClientSocketHandlerPool.AcquirePoolContent();
                if ( l_ClientSocketHandler == null )
                {
                    Debug.WriteLine( "Listener.OnAcceptor(...) - l_ClientSocketHandler == null error!" );

                    m_ClientHandlerAtServerPool.ReleasePoolContent( l_ClientHandlerAtServer );
                    m_SocketHandlerManagerAtServerPool.ReleasePoolContent( l_SocketHandlerManager );

                    return;
                }
                l_ClientSocketHandler.SetClientHandler( this, l_ClientHandlerAtServer );


                // out ServiceHandle
                clientHandlerAtServer = l_ClientHandlerAtServer;

                Monitor.Enter( m_LockAccepted );
                {
                    m_Accepted.Enqueue( l_ClientSocketHandler );
                }
                Monitor.Exit( m_LockAccepted );

                LOGs.WriteLine( LogMessageType.MSG_INFO, "新连接: {0}  [在线连接数 {1}] [总连接数 {2}]", nonceClientHandler.ClientAddress, allHandlerManager.OnlineClientCount, allHandlerManager.ClientCount );

                // 有新的连接过来需要发送全局信号处理新的连接
                if ( m_BaseWorld != null )
                    m_BaseWorld.SetWorldSignal();
                else
                    Debug.WriteLine( "Listener.OnAcceptor(...) - m_BaseWorld == null error!" );
            }
            else // 不允许连接
            {
                try
                {
                    nonceClientHandler.CloseSocket();
                }
                catch
                {
                    Debug.WriteLine( "Listener.OnAcceptor(...) - NonceClientHandler.CloseSocket(...) Exception error!" );
                }

                LOGs.WriteLine( LogMessageType.MSG_WARNING, "新连接: {0} 无法通过验证被断开! [在线连接数 {1}] [总连接数 {2}]", nonceClientHandler.ClientAddress, allHandlerManager.OnlineClientCount, allHandlerManager.ClientCount );
            }
        }
        #endregion
    }
}
#endregion

